package xyz.xtt.equity.mq;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.equity.api.enums.TblBenefitPackageEnum;
import xyz.xtt.equity.api.enums.UserBenefitSourceTypeEnum;
import xyz.xtt.equity.service.IBenefitService;
import xyz.xtt.equity.service.IInnerService;
import xyz.xtt.pay.api.enums.PayOrderBusinessTypeEnum;
import xyz.xtt.pay.client.response.TblPayOrderDto;

/**
 * 消费支付订单状态变更消息（目前仅消费购买玫瑰支付成功事件，用于发放vip权益）
 *
 * @author dale
 * @date 2025/2/13
 **/
@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.pay.order.status.change.topic:nft_pay_order_status_change}", selectorExpression = "ROSE_MINT:PAY_SUCCESS", consumerGroup = "${rocketmq.consumer.group.exchange:nft_consumer_exchange}")
public class PayOrderStatusChangeConsumer implements RocketMQListener<MessageExt> {
	@Autowired
	private IBenefitService benefitService;
	@Autowired
	private IInnerService iInnerService;

	@Override
	public void onMessage(MessageExt msg) {
		String msgId = msg.getMsgId();
		int reconsumeTimes = msg.getReconsumeTimes();
		String message = new String(msg.getBody(), StandardCharsets.UTF_8);
		log.info("PayOrderStatusChangeConsumer nft_pay_order_status_change msgId:{},reconsumeTimes:{},message: {}", msgId, reconsumeTimes, message);
		if (StringUtils.isEmpty(message)) {
			return;
		}
		if (!JSONUtil.isTypeJSON(message)) {
			log.warn("PayOrderStatusChangeConsumer nft_pay_order_status_change Received message: {} is not json", message);
			return;
		}
		try {
			TblPayOrderDto payOrderDto = JSONUtil.toBean(message, TblPayOrderDto.class);
			if (Objects.isNull(payOrderDto) || Objects.isNull(payOrderDto.getPayOrderId())) {
				log.warn("PayOrderStatusChangeConsumer nft_pay_order_status_change JSONUtil.toBean is null. message:{}", message);
				return;
			}
			// 检查payOrder是否存在
			TblPayOrderDto dbDataResult = iInnerService.fetchPayOrder(payOrderDto.getPayOrderId());
			if (Objects.isNull(dbDataResult)) {
				log.warn("PayOrderStatusChangeConsumer can not find payOrder Received message: {} is not exist", message);
				return;
			}

			if (Objects.equals(payOrderDto.getBusinessType(), PayOrderBusinessTypeEnum.ROSE_MINT.getCode())) {
				log.info("PayOrderStatusChangeConsumer nft_pay_order_status_change start to send month vip. payOrderId:{}", payOrderDto.getBusinessRefId());
				benefitService
						.recordAndSendFreeBenefitPackage(TblBenefitPackageEnum.NFT_VIP_MONTH.name(), payOrderDto
								.getAppUserId(), 1, UserBenefitSourceTypeEnum.BUY_ROSE_SEND_VIP_MONTH, payOrderDto.getPayOrderId());
			} else {
				log.warn("PayOrderStatusChangeConsumer nft_pay_order_status_change Received message: {} is not ROSE_MINT", message);
			}
		} catch (Exception e) {
			log.info("PayOrderStatusChangeConsumer consume failed. message:{} ex:{}", message, e.getMessage(), e);
			throw new RuntimeException("PayOrderStatusChangeConsumer Consumer Message exception", e);
		}
	}
}
